package com.ustc.hewei.rpc.server.net;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
* @description: netty网络通道中的处理器，处理请求消息
* @author hewei
* @date 2022/7/27 20:12
* @version 1.0
*/

@Slf4j
@ChannelHandler.Sharable
public class ChannelRequestHandler extends ChannelInboundHandlerAdapter {
    // ChannelInboundHandlerAdapter处理的是入站的IO操作，指的是从服务器端读取数据，所以有channelRead方法
    // ChannelOutboundHandlerAdapter处理的是出站的IO操作，指的是向服务器写入数据，应该有write方法

    private RequestHandler requestHandler;

    public ChannelRequestHandler(RequestHandler requestHandler) {
        this.requestHandler = requestHandler;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("服务端收到请求 {}", msg);
        ByteBuf receive = (ByteBuf) msg;
        byte[] res = new byte[receive.readableBytes()];
        receive.readBytes(res);
        receive.release();
        byte[] resp = requestHandler.handler(res);
        ByteBuf buffer = Unpooled.buffer(resp.length);
        buffer.writeBytes(resp);
        ctx.write(buffer);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error("出现异常，即将关闭网络通信! {}", cause.getMessage());
        ctx.close();
    }
}
